package cn.ainit.sys.print;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.junit.Test;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.mysql.jdbc.PreparedStatement;
import com.sun.xml.internal.bind.v2.model.core.ID;

import cn.ainit.sys.common.dao.SysBaseDao;
import cn.ainit.sys.ds.store.sysDataStore;
import cn.ainit.sys.dz.entity.SysDzSource;
import cn.ainit.sys.menu.SessionCont;
import cn.ainit.sys.print.entity.SysPrint;
import cn.ainit.sys.query.datastore.DataStore;

import javax.servlet.http.HttpServletRequest;


@Repository
public class PrintDaoImpl extends SysBaseDao implements PrintDao{

	@Override
	public List loadColumnsU(String dsId, String type, String flag, String uid)throws Exception {
		List columns = new ArrayList();
		if (uid == null || uid.equals("")) {
			throw new RuntimeException("用户没有登录");
		}
		try {
			if (dsId == null || dsId.equals(""))throw new RuntimeException("DS_ID 传入有误");
			//添加、详情界面
			String sql1 = "select WIDTH_ADD,HEIGHT_ADD,IS_PARENT_GROUP_ADD,GROUP_ID_ADD,ID_HIDDEN_GROUP_ADD,ORDER_NUM_ADD,COMMON_USE_ADD,HIDDEN_ADD,IS_SHOW_ADD,SINGLE_ROW_ADD,"+
			"FORMAT_FUNC_ADD,DEFAULT_VALUE_ADD,INPUTTYPE_ADD,EDITYPE_ADD,READONLY_ADD,REQUIRED_ADD,PK_FORMAT_ADD,IS_PK_ADD,JAVA_CLASS,"+
			"JAVA_PROPERTY,JAVA_PROPERTY_RECORDED,DS_ID,NAME,FORMAT_CONT,COLN_NAME,AUTO_ADD,AUTO_CONT_ADD,YUAN_DS_ID FROM SYS_COLUMNS  " +
			"WHERE DS_ID = '"+dsId+"' AND NAME NOT IN (select uc.column_name from sys_right_user_columns uc where uc.ds_id ='"+dsId+"' and uc.o_id = '"+uid+"' "+  
			" union select gc.column_name from sys_right_group_columns gc where gc.group_id in "+
			" (select g.group_id from sys_right_map g where g.o_id = '"+uid+"') and gc.ds_id = '"+dsId+"') AND ((IS_SHOW_ADD = 'T' AND JAVA_PROPERTY_RECORDED IS NOT NULL) "+  
			"OR (IS_PARENT_GROUP_ADD = 'T')) ORDER BY ORDER_NUM_ADD ";
			//查询常用条件
			String sql6 = "select WIDTH_QR,HEIGHT_QR,IS_PARENT_GROUP_QR,GROUP_ID_QR,ID_HIDDEN_GROUP_QR,ORDER_NUM_QR,COMMON_USE_QR,HIDDEN_QR,IS_SHOW_QR,SINGLE_ROW_QR,FORMAT_FUNC_QR,"+
			"DEFAULT_VALUE_QR,INPUTTYPE_QR,EDITYPE_QR,READONLY_QR,REQUIRED_QR,JAVA_CLASS,JAVA_PROPERTY_RECORDED,"+
			"JAVA_PROPERTY,DS_ID,NAME,COLN_NAME  FROM SYS_COLUMNS " +
			"WHERE DS_ID = '"+dsId+"' AND NAME NOT IN (select uc.column_name from sys_right_user_columns uc where uc.ds_id ='"+dsId+"' and uc.o_id = '"+uid+"' "+  
			" union select gc.column_name from sys_right_group_columns gc where gc.group_id in "+
			" (select g.group_id from sys_right_map g where g.o_id = '"+uid+"') and gc.ds_id = '"+dsId+"') AND ((IS_SHOW_QR = 'T' AND JAVA_PROPERTY_RECORDED IS NOT NULL AND COMMON_USE = 'T') "+  
			") ORDER BY ORDER_NUM_QR ";
			
			//查询条件界面
			String sql3 = "select WIDTH_QR,HEIGHT_QR,IS_PARENT_GROUP_QR,GROUP_ID_QR,ID_HIDDEN_GROUP_QR,ORDER_NUM_QR,COMMON_USE_QR,HIDDEN_QR,IS_SHOW_QR,SINGLE_ROW_QR,FORMAT_FUNC_QR,"+
			"DEFAULT_VALUE_QR,INPUTTYPE_QR,EDITYPE_QR,READONLY_QR,REQUIRED_QR,JAVA_CLASS,JAVA_PROPERTY_RECORDED,"+
			"JAVA_PROPERTY,DS_ID,NAME,COLN_NAME  FROM SYS_COLUMNS " +
			"WHERE DS_ID = '"+dsId+"' AND NAME NOT IN (select uc.column_name from sys_right_user_columns uc where uc.ds_id ='"+dsId+"' and uc.o_id = '"+uid+"' "+  
			" union select gc.column_name from sys_right_group_columns gc where gc.group_id in "+
			" (select g.group_id from sys_right_map g where g.o_id = '"+uid+"') and gc.ds_id = '"+dsId+"') AND ((IS_SHOW_QR = 'T' AND JAVA_PROPERTY_RECORDED IS NOT NULL) "+  
			"OR (IS_PARENT_GROUP_QR = 'T')) ORDER BY ORDER_NUM_QR ";
			//列表界面
			String sql4 = "select ORDERNUM,READONLY,REQUIRED,DEFAULT_VALUE,X,Y,WIDTH,HEIGHT,FIRSTPAGEFLAG,SECPAGEFLAG,SINGLE_ROW,ISSHOW,USE_BEFORE_VALUE,CUSTOM_PROPS,JAVA_CLASS,"+
			"JAVA_PROPERTY,IS_OPEN_LOAD_SAME,OPEN_LOAD_TYPE,LOAD_INIT_DATA_FUN,MEMO,IS_PK,CONFIG,FORMAT_CONT,"+
			"COMMON_USE,DS_ID,NAME,COLN_NAME,GROUP_NAME,PARENT_GROUP,GROUP_ID,GROUP_IS_OPEN,FORMAT,INPUTTYPE,EDITYPE,JAVA_PROPERTY_RECORDED,"+
			"HIDDEN,STYLER,ONCLICK,EDITOR,IS_PK_ADD,ROW_STYLER FROM SYS_COLUMNS " +
			"WHERE DS_ID = '"+dsId+"' AND NAME NOT IN (select uc.column_name from sys_right_user_columns uc where uc.ds_id ='"+dsId+"' and uc.o_id = '"+uid+"' "+  
			" union select gc.column_name from sys_right_group_columns gc where gc.group_id in "+
			" (select g.group_id from sys_right_map g where g.o_id = '"+uid+"') and gc.ds_id = '"+dsId+"') AND (ISSHOW = 'T' AND JAVA_PROPERTY_RECORDED IS NOT NULL) ORDER BY ORDERNUM ";
			if (type != null && !type.equals("")) {
				if (type.equals("1") || type.equals("2") || type.equals("5")) {//添加、查询、修改界面
					columns = this.getJdbcTemplate().queryForList(sql1);
				}else if(type.equals("3")){//查询条件界面
					columns = this.getJdbcTemplate().queryForList(sql3);
				}else if(type.equals("4")|| type.equals("44")){//查询界面
					columns = this.getJdbcTemplate().queryForList(sql4);
				}else if(type.equals("6")){//查询常用条件
					columns = this.getJdbcTemplate().queryForList(sql6);
				}
			}
			this.getJdbcTemplate().queryForList(sql1);
		} catch (Exception e) {
			throw e;
		}
		return columns;
	}
	
	
	
	

	@Override
	public SysDzSource getSysDzSource(String dzId) throws Exception {
		String hql = " from SysDzSource dz where dz.dzId = ?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, dzId);
		List<SysDzSource> list = query.list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public String getShowNameVal(String sql) throws Exception {
		String  data=null;
		try {
			data = jdbcTemplate.queryForObject(sql,String.class);  
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	@Override
	public SysPrint getPrintObj(String dsId, String name) throws Exception {
		List<SysPrint> list=null;
		try {
			String hql="from SysPrint where id.dsId=? and id.name=?";
			Query query=sessionFactory.getCurrentSession().createQuery(hql);
			query.setString(0, dsId);
			query.setString(1, name);
			list = query.list();
			System.out.println(list.size());
			if (list != null && list.size() > 0) {
				return list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

/*	public static void main(String[] args) {
		List<SysPrint> list=null;
		try {
			String hql="from SysPrint where id.dsId=? and id.name=?";
			Query query=sessionFactory.getCurrentSession().createQuery(hql);
			query.setString(0, "ds_fx_xs2");
			query.setString(1, "");
			list = query.list();
			System.out.println(list.size());
			if (list != null && list.size() > 0) {
				return list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(list.size());
	}*/
	
	
	@Override
	public Object gePrintDataBySql(String sql,String pkVal)throws Exception{
		List<Map<String, Object>> data=new ArrayList();
		Map newData = new HashMap<String, Object>();
		Object[] keys = null;
		if(sql!=""&&sql!=null){
			data=this.jdbcTemplate.queryForList(sql,new Object[] {pkVal});
			for (int i = 0; i < data.size(); i++) {
				newData = (HashMap<String, Object>) data.get(i);
					keys = newData.keySet().toArray();
				for (int j = 0; j < keys.length;j++) {
					data.get(i).put(keys[j].toString(), (newData.get(keys[j])==null?"":newData.get(keys[j])).toString().replaceAll("\t","&nbsp;&nbsp;&nbsp;&nbsp;"));  //替换tab
					data.get(i).put(keys[j].toString(), (newData.get(keys[j])==null?"":newData.get(keys[j])).toString().replaceAll(" ","&nbsp;"));//替换空格
					data.get(i).put(keys[j].toString(), (newData.get(keys[j])==null?"":newData.get(keys[j])).toString().replaceAll("\\n","<br>")); //替换换行
				}
			}
			if(data!=null&&data.size()>0){
				return data.get(0);
			}
		}
		return null;
	}

	
	@Test
	public  void test() {
        String str = "aaa    bbb";//替换成aaa---bbb
        str = str.replaceAll("\\s+?", "-");
//        str = str.replaceAll(" ", "&nbsp;");
        System.out.println(str);//aaa---bbb
    }
	@Override
	public List<Map<String,Object>> getPrintMMList(String sql) {
		List<Map<String,Object>> list   = this.jdbcTemplate.queryForList(sql);
		return list;
	}
	
	@Override
	public List getPrintMList(String sql, String pkVal, String config) {
		List data=new ArrayList();
		if(config!=null&&!"".equals(config.trim())){
			String[] conList = config.split(";");
			Map<String, String> map1 = new HashMap<String, String>();
			for (int i = 0; i < conList.length; i++) {
				String[] thenStr = conList[i].split("-");
				map1.put(thenStr[0],thenStr[1]);
			}
		}
		//获取占位符的个数，并且是相同的变量值
		List params=new ArrayList();
		if(sql!=""&&sql!=null){
			char[] chars = sql.toCharArray();
			for(int i = 0; i < chars.length; i++)
			{
			    if("?".equals((chars[i]+"")))
			    {
			    	params.add(pkVal);
			    }
			} 
		}
		Object[] pms=new Object[params.size()];
		for (int i = 0; i < pms.length; i++) {
			pms[i]=params.get(i);
		}
		data=this.jdbcTemplate.queryForList(sql,pms);
		return data;
	}

	@Override
	public List getPrintQueryData(String zSql) throws Exception {
		return this.jdbcTemplate.queryForList(zSql);
	}
	
	
	@Override
	public Map<String, Object> getCompanyInfo() throws Exception {
		String sql = " SELECT * FROM bs_owner ";
		Map<String, Object> comHashMap = new HashMap<String, Object>();
		List<Map<String, Object>> comList = this.getJdbcTemplate().queryForList(sql);
		if (comList != null && !comList.isEmpty()) {
			comHashMap = comList.get(0);
		}
		return comHashMap;
	}





	@Override
	public List getsyscl(String dsid) {
		String sqlString="select * from sys_columns s where s.ds_id='"+dsid+"' and nvl(s.hidden,'F')<>'T'  and s.isshow='T' and s.java_property_recorded is not null order by s.ordernum";
		List list=this.getJdbcTemplate().queryForList(sqlString);
		return list;
	}


    @Override
    public Boolean countUpdate(HttpServletRequest request) {
        String tpye = request.getParameter("type");
        String dsId = request.getParameter("dsId");
        String uid  =request.getSession().getAttribute(SessionCont.uid).toString();

        List<Map<String, Object>> list = this.jdbcTemplate.queryForList("SELECT * FROM SYS_DATASTORE where DS_ID='"+ dsId +"'");
        String tableName =  list.get(0).get("UPDATE_TABLE").toString();

        if("0".equals(tpye)){
            String pfks	= request.getParameter("pfks");
            String pkVal = request.getParameter("pkVal");
            String sql_ ="select PRINT_NUM from "+tableName+" where "+pfks+"='"+pkVal+"'";
            int num =this.jdbcTemplate.queryForInt(sql_);
            num++;
            String sql = "UPDATE "+tableName+" set PRINT_NUM="+num+",PRINT_MAN='"+uid+"',PRINT_DATE=to_date(to_char(sysdate,'yyyy-MM-dd HH24:mi:ss'),'yyyy-mm-dd,hh24:mi:ss') where "+pfks+"='"+pkVal+"' ";
            this.jdbcTemplate.execute(sql);

        }else if("1".equals(tpye)){
            String key = request.getParameter("key");
            String valStr =	request.getParameter("valStr");
            valStr = valStr.substring(0,valStr.length()-1);
            String sql_ ="select "+key+",PRINT_NUM from "+tableName+" where "+key+" in ("+valStr+")";
            List<Map<String, Object>> list_ = this.jdbcTemplate.queryForList(sql_);
            for(int i=0;i<list_.size();i++){
                String key_ = list_.get(i).get(key).toString();
                int num = Integer.parseInt(list_.get(i).get("PRINT_NUM")==null?"0":list_.get(i).get("PRINT_NUM").toString())+1;
                String sql = "UPDATE "+tableName+" set PRINT_NUM="+num+",PRINT_MAN='"+uid+"',PRINT_DATE=to_date(to_char(sysdate,'yyyy-MM-dd HH24:mi:ss'),'yyyy-mm-dd,hh24:mi:ss') where "+key+"='"+key_+"'";
                this.jdbcTemplate.execute(sql);
            }

        }
        return true;
    }
	
}


